<template>
  <div class="min-h-screen bg-gradient-to-br from-[#E8F1FF] to-[#C5DCFF] flex items-center justify-center p-4">
    <div class="w-full max-w-2xl bg-white rounded-lg shadow-lg overflow-hidden">
      <!-- 步骤1：选择考试类型 -->
      <div v-if="step === 1" class="p-8">
        <h1 class="text-2xl font-bold text-gray-800 mb-6">选择考试类型</h1>
        <div class="space-y-4">
          <button
            @click="selectExamType('daily')"
            class="w-full p-4 text-left bg-white hover:bg-gray-50 border rounded-lg transition duration-300 flex items-center justify-between"
          >
            <span class="text-lg font-medium">今日测验</span>
            <ChevronRightIcon class="h-5 w-5" />
          </button>
          <button
            @click="selectExamType('consolidation')"
            class="w-full p-4 text-left bg-white hover:bg-gray-50 border rounded-lg transition duration-300 flex items-center justify-between"
          >
            <span class="text-lg font-medium">巩固测验</span>
            <ChevronRightIcon class="h-5 w-5" />
          </button>
        </div>
      </div>

      <!-- 步骤2：配置测验 -->
      <div v-if="step === 2" class="p-8">
        <button @click="step = 1" class="mb-4 text-gray-600 hover:text-gray-800 transition duration-300">
          <ArrowLeftIcon class="h-6 w-6" />
        </button>
        <h1 class="text-2xl font-bold text-gray-800 mb-6">配置测验</h1>
        <div class="space-y-6">
          
          <!-- 文档材料选择(仅巩固测验) -->
          <div v-if="examType === 'consolidation'">
            <label class="block text-sm font-medium text-gray-700 mb-2">选择文档</label>
            <select
              v-model="selectedDocument"
              class="w-full p-2 border rounded-md bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            >
              <option value="">请选择文档</option>
              <option v-for="doc in documents" :key="doc.id" :value="doc.id">
                {{ doc.title }}  
              </option>
            </select>
          </div>

          <!-- 难度选择 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">难度</label>
            <select 
              v-model="difficulty" 
              class="w-full p-2 border rounded-md bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            >
              <option value="easy">简单</option>
              <option value="medium">中等</option>
              <option value="hard">困难</option>
            </select>
          </div>

          <!-- 题目类型 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">题目类型</label>
            <div class="space-y-2">
              <label v-for="type in availableTypes" :key="type.value" class="flex items-center">
                <input 
                  type="radio" 
                  v-model="questionTypes" 
                  :value="type.value"
                  class="rounded text-blue-600 focus:ring-blue-500 h-4 w-4"
                >
                <span class="ml-2">{{ type.label }}</span>
              </label>
            </div>
          </div>

          <!-- 题目数量 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">题目数量</label>
            <input 
              v-model.number="questionCount" 
              type="number" 
              min="1" 
              max="50"
              class="w-full p-2 border rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            >
          </div>

          

          <!-- 生成测验按钮 -->
          <button 
            @click="generateExam"
            :disabled="!isValidConfig"
            class="w-full bg-blue-600 text-white p-3 rounded-md hover:bg-blue-700 transition duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            生成测验
          </button>
        </div>
      </div>

      <!-- 步骤3：答题界面 -->
      <div v-if="step === 3" class="p-8">
        <div class="flex justify-between items-center mb-6">
          <h1 class="text-2xl font-bold text-gray-800">今日测验</h1>
          <div class="text-gray-600">{{ currentQuestionIndex + 1 }} / {{ questions.length }}</div>
        </div>

        <!-- 当前题目 -->
        <div v-if="currentQuestion" class="mb-8">
          <h2 class="text-xl font-semibold mb-4">
            问题 {{ currentQuestionIndex + 1 }}: {{ currentQuestion.text }}
          </h2>

          <!-- 选项区域 -->
          <div class="space-y-3">
            <template v-if="currentQuestion.type === 'single' || currentQuestion.type === 'multiple'">
              <label 
                v-for="(option, optionIndex) in currentQuestion.options" 
                :key="`question-${currentQuestionIndex}-${optionIndex}`"
                class="flex items-center p-3 border rounded-md hover:bg-gray-50 cursor-pointer"
                :class="{
                  'border-green-500 bg-green-50': isCorrectOption(currentQuestion, option),
                  'border-red-500 bg-red-50': isIncorrectOption(currentQuestion, option)
                }"
              >
                <input 
                  :type="currentQuestion.type === 'single' ? 'radio' : 'checkbox'"
                  :name="`question-${currentQuestionIndex}`"
                  :value="option"
                  v-model="currentQuestion.userAnswer"
                  :disabled="currentQuestion.answered"
                  class="mr-3"
                >
                <span>{{ option }}</span>
              </label>
            </template>

            <template v-else-if="currentQuestion.type === 'fillBlank'">
              <input 
                type="text"
                v-model="currentQuestion.userAnswer"
                :disabled="currentQuestion.answered"
                class="w-full p-2 border rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                placeholder="请输入答案"
              >
            </template>
          </div>

          <!-- 答案解析 -->
          <div 
            v-if="currentQuestion.showExplanation" 
            class="mt-4 p-4 bg-gray-50 rounded-md"
          >
            <h3 class="font-semibold text-gray-800 mb-2">解析:</h3>
            <p class="text-gray-700">{{ currentQuestion.explanation }}</p>
          </div>
        </div>

        <!-- 导航按钮 -->
        <div class="flex justify-between mt-6">
          <button 
            @click="previousQuestion" 
            :disabled="currentQuestionIndex === 0"
            class="px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700 transition duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            上一题
          </button>
          <button 
            v-if="currentQuestionIndex < questions.length - 1"
            @click="nextQuestion" 
            class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition duration-300"
          >
            下一题
          </button>
          <button 
            v-else
            @click="finishExam" 
            class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition duration-300"
          >
            完成测验
          </button>
        </div>
      </div>

      <!-- 步骤4：结果页面 -->
      <div v-if="step === 4" class="p-8">
        <h1 class="text-2xl font-bold text-gray-800 mb-8">成绩</h1>

        <!-- 题目导航 -->
        <div class="mb-8">
          <div class="flex flex-wrap gap-2">
            <div
              v-for="(question, index) in questions"
              :key="index"
              class="w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium"
              :class="{
                'bg-green-400 text-white': isCorrect(question),
                'bg-red-400 text-white': isWrong(question),
                'bg-gray-200 text-gray-600': isUnanswered(question)
              }"
            >
              {{ index + 1 }}
            </div>
          </div>
        </div>

        <!-- 成绩图表 -->
        <div class="mb-8">
          <canvas ref="chartRef" class="max-w-[300px] mx-auto"></canvas>
        </div>

        <!-- 详细统计 -->
        <div class="flex justify-center gap-8 mb-8">
          <div class="flex items-center gap-2">
            <div class="w-3 h-3 rounded-full bg-green-400"></div>
            <span class="text-gray-600">正确: {{ correctCount }}</span>
          </div>
          <div class="flex items-center gap-2">
            <div class="w-3 h-3 rounded-full bg-red-400"></div>
            <span class="text-gray-600">错误: {{ wrongCount }}</span>
          </div>
          <div class="flex items-center gap-2">
            <div class="w-3 h-3 rounded-full bg-gray-200"></div>
            <span class="text-gray-600">未回答: {{ unansweredCount }}</span>
          </div>
        </div>

        <!-- 用时 -->
        <div class="mb-8">
          <h2 class="text-xl font-bold text-gray-800 mb-2">用时</h2>
          <p class="text-2xl font-mono">{{ formatTime(examTime) }}</p>
        </div>

        <!-- 重新开始按钮 -->
        <button 
          @click="restartExam" 
          class="w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition duration-300"
        >
          重新开始测验
        </button>
      </div>
    </div>

    <!-- 添加等待框 -->
    <div v-if="isLoading" class="fixed inset-0 flex flex-col items-center justify-center bg-black bg-opacity-50 z-50">
      <div class="animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-blue-500 mb-4"></div>
      <div class="text-white text-xl">正在生成试题,请等待...</div>
    </div>
    <showMessage ref="showMessageRef"/> 
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ChevronRightIcon, ArrowLeftIcon } from 'lucide-vue-next'
import Chart from 'chart.js/auto'
import axiosClient from '@/utils/axios'
import showMessage from '@/components/share/showMessage.vue'

// 基础状态
const step = ref(1)
const difficulty = ref('medium')
const questionTypes = ref([])
const questionCount = ref(3)
const questions = ref([])
const currentQuestionIndex = ref(0)
const chartRef = ref(null)
const showMessageRef = ref(null)
let chart = null

// 计时相关
const examStartTime = ref(0)
const examTime = ref(0)
const examTimer = ref(null)

// 可选题目类型
const availableTypes = [
  { value: 'single', label: '单选题' },
  { value: 'multiple', label: '多选题' },
  { value: 'fillBlank', label: '简答题' },
  { value: 'comprehensive', label: '综合题' }
]

// 计算属性
const currentQuestion = computed(() => questions.value[currentQuestionIndex.value])
const correctCount = computed(() => {
  return questions.value.filter(isCorrect).length;
});
const wrongCount = computed(() => {
  return questions.value.filter(isWrong).length;
});
const unansweredCount = computed(() => {
  return questions.value.filter(isUnanswered).length;
});
const correctRate = computed(() => ((correctCount.value / questions.value.length) * 100).toFixed(2));
const isValidConfig = computed(() => questionTypes.value.length > 0 && questionCount.value > 0)

// 添加isLoading状态
const isLoading = ref(false)

// 考试类型
const examType = ref('daily')

// 选择的文档(仅巩固测验)
const selectedDocument = ref('')

// 可选文档列表(仅巩固测验)
const documents = ref([])

// 方法
const selectExamType = (type) => {
  examType.value = type
  step.value = 2
}

const generateExam = async () => {
  try {
    if (questionCount.value > 30) {
      showMessageRef.value.showMessage('题目数量不能大于30', 'BUG')
      return
    }
    isLoading.value = true
    let response
    if (examType.value === 'daily') {
      response = await axiosClient.post('/agent/getToDayExam', {
        text: '',
        num_questions: questionCount.value,
        question_types: questionTypes.value,
        difficulty: difficulty.value
      }, { timeout: 0 })
    } else if (examType.value === 'consolidation') {
      // TODO: 调用巩固测验的接口,传入选择的文档ID
      response = await generateConsolidationExam(selectedDocument.value)
    }

    questions.value = response.data.questions.map((item, index) => ({
      id: index + 1,
      type: item.type,
      text: item.text,
      options: item.options,
      correctAnswer: item.correctAnswer,
      userAnswer: [],
      explanation: item.explanation,
      showExplanation: false,
      answered: false
    }));

    currentQuestionIndex.value = 0;

    // 开始计时
    examStartTime.value = Date.now();
    examTimer.value = setInterval(() => {
      examTime.value = Math.floor((Date.now() - examStartTime.value) / 1000);
    }, 1000);

    step.value = 3;
    showMessageRef.value.showMessage('试题生成成功!', 'INFO') // 显示成功消息
  } catch (error) {
    console.error('生成测验失败:', error);
    showMessageRef.value.showMessage('试题生成失败,请重试!', 'BUG') // 显示错误消息
  } finally {
    isLoading.value = false // 结束加载
  }
};

const checkAnswer = () => {
  const question = currentQuestion.value
  if (!question) return

  question.showExplanation = true
  question.answered = true
}

const isCorrectOption = (question, option) => {
  return question.answered && question.correctAnswer.includes(option)
}

const isIncorrectOption = (question, option) => {
  return question.answered && question.userAnswer.includes(option) && !question.correctAnswer.includes(option)
}

const nextQuestion = () => {
  const question = currentQuestion.value
  if (!question) return

  if (!question.answered) {
    checkAnswer()
  } else {
    if (currentQuestionIndex.value < questions.value.length - 1) {
      currentQuestionIndex.value++
      question.answered = false
      question.showExplanation = false
    }
  }
}

const previousQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--
  }
}

const finishExam = () => {
  const question = currentQuestion.value
  if (!question) return
  
  if (!question.answered) {
    checkAnswer()
  } else {
    if (examTimer.value) {
      clearInterval(examTimer.value)
    }
    question.answered = false
    question.showExplanation = false
    step.value = 4
  }
}

const restartExam = () => {
  step.value = 1
  questions.value = []
  currentQuestionIndex.value = 0
  difficulty.value = 'medium'
  questionTypes.value = []
  questionCount.value = 10
  examTime.value = 0
  if (examTimer.value) {
    clearInterval(examTimer.value)
  }
}

const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`
}

const createChart = () => {
  const ctx = chartRef.value.getContext('2d')

  if (chart) {
    chart.destroy()
  }

  chart = new Chart(ctx, {
    type: 'doughnut',
    data: {
      labels: ['正确', '错误', '未回答'],
      datasets: [{
        data: [correctCount.value, wrongCount.value, unansweredCount.value],
        backgroundColor: ['#4ADE80', '#FB7185', '#E5E7EB'],
        borderWidth: 0,
        cutout: '75%'
      }]
    },
    options: {
      responsive: true,
      plugins: {
        legend: {
          display: false
        },
        title: {
          display: false
        },
        tooltip: {
          enabled: false
        }
      }
    }
  })

  // 添加中心文字
  const originalDraw = chart.draw
  chart.draw = function() {
    originalDraw.apply(this, arguments)

    const width = this.width
    const height = this.height
    const ctx = this.ctx

    ctx.restore()
    ctx.font = '20px Arial'
    ctx.fillStyle = '#000'
    ctx.textBaseline = 'middle'

    const text = `${correctRate.value}%`
    const textWidth = ctx.measureText(text).width

    ctx.fillText(text, (width - textWidth) / 2, height / 2)
    ctx.fillText('正确率', (width - ctx.measureText('正确率').width) / 2, height / 2 + 25)

    ctx.save()
  }
}

// 监听步骤变化，创建图表
onMounted(() => {
  watch(() => step.value, (newStep) => {
    if (newStep === 4) {
      setTimeout(() => {
        createChart()
      }, 0)
    }
  })
})

// 判断函数
const isCorrect = (question) => {
  if (question.answered) {
    return false
  }

  if (question.type === 'single' || question.type === 'multiple') {
    // 需要将question.userAnswer转换为数组
    question.userAnswer = Array.isArray(question.userAnswer) ? question.userAnswer : [question.userAnswer]
    return question.userAnswer && question.userAnswer.length > 0 && question.userAnswer.every(a => question.correctAnswer.includes(a));
  } else if (question.type === 'fillBlank') {
    return question.userAnswer === question.correctAnswer[0];
  }
};

const isWrong = (question) => {
  if (question.answered) {
    return false
  }

  if (question.type === 'single' || question.type === 'multiple') {
    // 需要将question.userAnswer转换为数组
    question.userAnswer = Array.isArray(question.userAnswer) ? question.userAnswer : [question.userAnswer]
    return question.userAnswer && question.userAnswer.length > 0 && !question.userAnswer.every(a => question.correctAnswer.includes(a));
  } else if (question.type === 'fillBlank') {
    return question.userAnswer && question.userAnswer !== question.correctAnswer[0];
  }
};

const isUnanswered = (question) => {
  if (question.answered) {
    return false
  }
  return !question.userAnswer || question.userAnswer.length === 0;
};

// TODO: 实现巩固测验的生成逻辑
const generateConsolidationExam = async (documentId) => {
  try {
    const response = await axiosClient.post('/agent/getConsolidationExam', {
      text: '',
      material_id: documentId,
      num_questions: questionCount.value,
      question_types: questionTypes.value,
      difficulty: difficulty.value
    }, { timeout: 0 })
    
    return response
  } catch (error) {
    console.error('生成巩固测验失败:', error)
    throw error
  }
}

// 获取文档材料列表
const fetchDocuments = async () => {
  try {
    const response = await axiosClient.get('/materials/')
    documents.value = response.data
  } catch (error) {
    console.error('获取文档材料失败:', error)
    // 这里可以根据需要进行错误处理,如显示错误提示等
  }
}

// 在组件挂载时获取文档材料列表
onMounted(() => {
  fetchDocuments()
})
</script>